"use strict";
const path = require("path");

// 自定义工具类库
const log = require("@wenjun-cli/log");
const Package = require("@wenjun-cli/package");
const { exec: spawn } = require("@wenjun-cli/utils");

// 脚手架包名映射
const SETTINGS = {
  init: "@wenjun-cli/init",
  add: "@wenjun-cli/add",
  publish: "@wenjun-cli/publish",
  login: "@wenjun-cli/login",
  addUser: "@wenjun-cli/addUser",
};
const CACHE_DIR = "dependencies";

async function exec() {
  let targetPath = process.env.CLI_TARGET_PATH;
  const homePath = process.env.CLI_HOME_PATH;
  let storeDir = "";
  let pkg;
  log.verbose("exec-- targetPath", targetPath);
  log.verbose("exec-- homePath", homePath);
  const cmdObj = arguments[arguments.length - 1];
  const cmdName = cmdObj.name();
  log.verbose("exec-- cmdName", cmdName);
  const packageName = SETTINGS[cmdName];
  log.verbose("exec-- packageName", packageName);
  const packageVersion = "latest";
  if (!targetPath) {
    // 生成缓存路径
    targetPath = path.resolve(homePath, CACHE_DIR);
    storeDir = path.resolve(targetPath, "node_modules");
    log.verbose("targetPath", targetPath);
    log.verbose("storeDir", storeDir);
    pkg = new Package({
      targetPath,
      storeDir,
      packageName,
      packageVersion,
    });
    if (await pkg.exists()) {
      // 更新package
      await pkg.update();
      console.log("?????? 更新package");
    } else {
      // 安装package
      console.log("?????? 安装package");
      await pkg.install();
    }
  } else {
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion,
    });
  }
  const rootFile = pkg.getRootFilePath();
  log.verbose("exec-- rootFile", rootFile);
  if (rootFile) {
    try {
      //在当前的主线程中调用
      // require(rootFile).call(null, Array.from(arguments));
      // 配置在node的子进程中进行调用，合理分配CPU资源
      const args = Array.from(arguments);
      const cmd = args[args.length - 1];
      const o = Object.create(null);
      Object.keys(cmd).forEach((key) => {
        if (
          cmd.hasOwnProperty(key) &&
          !key.startsWith("_") &&
          key !== "parent"
        ) {
          o[key] = cmd[key];
        }
      });
      args[args.length - 1] = o;
      const code = `require('${rootFile}').call(null, ${JSON.stringify(
        args
      )});`;
      const child = spawn("node", ["-e", code], {
        cwd: process.cwd(),
        stdio: "inherit",
      });
      child.on("error", (err) => {
        log.error("error", err.message);
        process.exit(1); // 返回错误信息，子进程中断执行
      });
      child.on("exit", (msg) => {
        // log.verbose("exit", "命令执行成功：" + msg);
        process.exit(msg); // 命令执行成功，子进程中断执行
      });
    } catch (err) {
      log.error(err.message);
    }
  }
}

module.exports = exec;
